package com.zzy.database.service.Impl;

import com.zzy.database.mapper.CustomerMapper;
import com.zzy.database.mapper.EmployeeMapper;
import com.zzy.database.mapper.PasswordMapper;
import com.zzy.database.pojo.User;
import com.zzy.database.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;


@Service
public class UserServiceImpl implements UserService {


    @Autowired
    private PasswordMapper passwordMapper;

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public User findUserByNameAndType(User user) {
        String username = user.getUsername();
        String userType = user.getUserType();
        System.out.println(userType);

        String userId = null;
        if ("客户".equals(userType)) {
            userId =customerMapper.findCustomerIdByUsername(username);
        } else if ("员工".equals(userType)) {
            userId = employeeMapper.findEmployeeIdByUsername(username);
            System.out.println(userId);
        }

        if (userId == null) {
            return null; // 用户不存在
        }

        String dbPassword = passwordMapper.getPasswordByUserId(userId);
        user.setPassword(dbPassword); // 设置密码用于验证
        user.setId(userId);
        return user;
    }
    @Override
    public void register(User user) {
        String userId = UUID.randomUUID().toString();
        user.setId(userId);

        if ("客户".equals(user.getUserType())) {
            customerMapper.insertCustomer(userId,user.getUsername());
        } else {
            System.out.println(user.getUsername());
           employeeMapper.insertEmployee(userId,user.getUsername());
        }

        String encryptedPwd =user.getPassword();
        passwordMapper.insertPassword(userId, encryptedPwd);

    }

    @Override
    public boolean changepasswd(User user, String oldPassword, String newPassword) {
        String id=null;
        if("客户".equals(user.getUserType())){
             id=customerMapper.findCustomerIdByUsername(user.getUsername());
        }else {
            id=employeeMapper.findEmployeeIdByUsername(user.getUsername());
        }
        String passwordByUserId = passwordMapper.getPasswordByUserId(id);
        if(passwordByUserId.equals(oldPassword)){
            passwordMapper.updatepasswd(id,newPassword);
            return true;
        }
        else {
            return false;
        }

    }
}
